package com.xunfang.service.impl;

import com.xunfang.bean.MenuVo;
import com.xunfang.bean.Permission;
import com.xunfang.service.IMenuService;
import com.xunfang.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yellow Docter
 * @date 2023 -11-01
 * @desc
 */
@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public List<MenuVo> findMenuByUsername(String username) {

        //01 查询 用户的对应的权限菜单
        List<Permission> permissions = permissionService.findPermissionByUsername(username);
        //02 把权限菜单转成 页面的 menuVo对象
        //创建 集合 存储 MenuVo
        List<MenuVo> menuVos = new ArrayList<>();
        for (Permission permission : permissions) {
            if (permission.getLevel() == 1){ //判断是否为 父级菜单
                //permission 转成  menuVo
                MenuVo menuVo = new MenuVo();
                menuVo.setId(permission.getId());
                menuVo.setPath(String.valueOf(permission.getSort()));
                menuVo.setTitle(permission.getPname());
                //menuVo.setLinkUrl();
                menuVo.setIcon(permission.getIcon());

                List<MenuVo> children = new ArrayList<>();

                for (Permission per : permissions) {
                    if (per.getParentId() == permission.getId()){

                        MenuVo menu = new MenuVo();
                        menu.setId(per.getId());
                        menu.setPath(String.valueOf(per.getSort()));
                        menu.setTitle(per.getPname());
                        menu.setLinkUrl(per.getUrl());
                        children.add(menu);
                    }
                }
                menuVo.setChildren(children);  // 查询子菜单
                menuVos.add(menuVo);
            }
        }
        return menuVos;
    }

}
